//配置axios
import axios from "axios";
//引入elementUi的弹框
import { MessageBox, Message, Loading } from "element-ui";
//引入storage方法
import storage from "@/utils/storage";
let http = axios.create({
  baseURL: "/api",
  timeout: 5000, //超时设置
  withCredentials: true, //携带本地凭据 比如cookie
});

//全局的请求拦截器 对接口的请求批量进行统一处理
let fullScreenLoading = null;
http.interceptors.request.use((config) => {
  //获取本地的token，携带给后端
  let token = storage.get("qf-token");
  config.headers["authorization"] = token;

  //登入时打开加载动画，请求地址包含关键字：login、wechatLogin
  if (
    config.url.indexOf("login") !== -1 ||
    config.url.indexOf("wechatLogin") !== -1
  ) {
    fullScreenLoading = Loading.service({
      lock: true,
      text: "Loading",
      spinner: "el-icon-loading",
      background: "rgba(0, 0, 0, 0.7)",
    });
  }

  return config; //放行 不return 那么不能将请求真正的发送出去
});

//全局响应拦截 统一对错误进行处理

http.interceptors.response.use((config) => {
  if (fullScreenLoading) {
    fullScreenLoading.close();
    fullScreenLoading = null;
  }
  let { state, msg } = config.data;
  if (!state) {
    MessageBox({
      message: msg,
      title: "错误提示",
      type: "error",
    });
  }
  //后台设置10022、1004这两个状态码分别对应token过期和session过期
  //10026没有权限
  //清除本地缓存、清除token
  let { code } = config.data;
  if (code === "10022" || code === "10004") {
    Message.error("登入过期，请重新登入");
    storage.rm("qf-token");
    location.reload();
  }
  return config; //如果不return axios请求就拿不到响应结果
});

export default http;
